package com.google.code.gaestats;

import com.google.appengine.api.NamespaceManager;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Result;
import java.util.Map;

/**
 *
 * @author JaggardM
 */
public class StatsObjectify
{

	private String oldNamespace = null;
	static final String NAMESPACE = "gaestats";
	private Objectify ofy;

	protected StatsObjectify(Objectify ofy)
	{
		this.ofy = ofy;
	}

	public CounterNames getCounterNames()
	{
		before();
		try
		{
			return ofy.load().type(CounterNames.class).id(1).get();
		}
		finally
		{
			after();
		}
	}

	public void putCounterNames(CounterNames cn)
	{
		before();
		try
		{
			ofy.save().entity(cn).now();
		}
		finally
		{
			after();
		}
	}

	public Map<String, Counter> loadAllDataForCounters(Iterable<String> names)
	{
		before();
		try
		{
			return ofy.load().group("Hour").type(Counter.class).ids(names);
		}
		finally
		{
			after();
		}
	}

	public Map<String, Counter> loadAllDataForCounters(String... names)
	{
		before();
		try
		{
			return ofy.load().group("Hour").type(Counter.class).ids(names);
		}
		finally
		{
			after();
		}
	}

	public Map<String, Counter> loadMinuteDataForCounters(String... names)
	{
		before();
		try
		{
			return ofy.load().group("Minute").type(Counter.class).ids(names);
		}
		finally
		{
			after();
		}
	}

	public Map<String, Counter> loadMinuteDataForCounters(Iterable<String> names)
	{
		before();
		try
		{
			return ofy.load().group("Minute").type(Counter.class).ids(names);
		}
		finally
		{
			after();
		}
	}

	public void save(PerMinuteCounterData pmcd, PerHourCounterData phcd, Counter cntr)
	{
		before();
		try
		{
			Result<Key<PerMinuteCounterData>> pmcdRK = ofy.save().entity(pmcd);
			Result<Key<PerHourCounterData>> phcdRK = ofy.save().entity(phcd);
			Key<PerMinuteCounterData> pmcdK = pmcdRK.now();
			Key<PerHourCounterData> phcdK = phcdRK.now();
			cntr.hourData = Ref.create(phcdK);
			cntr.minuteData = Ref.create(pmcdK);
			ofy.save().entity(cntr);
		}
		finally
		{
			after();
		}
	}

	private void before()
	{
		oldNamespace = NamespaceManager.get();
		NamespaceManager.set(NAMESPACE);
	}

	private void after()
	{
		NamespaceManager.set(oldNamespace);
	}
}
